package generator.util;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.experimental.UtilityClass;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * </p>
 *
 * @author angel.bin@aliyun.com
 * @since 2020-10-05 13:35
 */
@UtilityClass
public class TemplateUtils {

    /**
     * 根据模板生成本地文件
     *
     * @param baseDir      模板的父目录
     * @param dataModel    数据变量
     * @param outPath      输出的路径
     * @param templateName 模板的名称
     * @throws IOException
     * @throws TemplateException
     */
    public void processFile(File baseDir, Object dataModel, File outPath, String templateName) throws TemplateException {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        String encode = StandardCharsets.UTF_8.name();
        configuration.setDefaultEncoding(encode);
        try (FileWriter fileWriter = new FileWriter(outPath, StandardCharsets.UTF_8)) {
            TemplateLoader templateLoader = new FileTemplateLoader(baseDir);
            configuration.setTemplateLoader(templateLoader);
            Template template = configuration.getTemplate(templateName, encode);
            template.process(dataModel, fileWriter);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符串模板
     *
     * @param templateContext 模板内容
     * @param dataModel       数据
     * @param templateName    模板名称
     * @return 模板根据变量生成的字符串
     * @throws TemplateException
     */
    public String processString(String templateContext, Object dataModel, String templateName) throws TemplateException {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        String encode = StandardCharsets.UTF_8.name();
        configuration.setDefaultEncoding(encode);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate(templateName, templateContext);
        configuration.setTemplateLoader(stringTemplateLoader);
        String context = null;
        try (StringWriter stringWriter = new StringWriter()) {
            Template template = configuration.getTemplate(templateName, encode);
            template.process(dataModel, stringWriter);
            context = new String(stringWriter.getBuffer());
            stringWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return context;
    }

}
